﻿using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.JSON;
using Kingdee.BOS.KDThread;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using RK.Model.Ronma;
using RK.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RK.ListBillPlugin.Ronma
{
    [Description("Ronma:手动同步采购件库存报表"), HotUpdate]
    public class ListPurInvReportToOA : AbstractListPlugIn
    {
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            //手动同步OA状态
            if (e.BarItemKey.EqualsIgnoreCase("tb_PurInvRerport"))
            {
                ShowProgressBar(true, this.Context);
            }
        }

        private void ShowProgressBar(bool userTruePro, Kingdee.BOS.Context ctx)
        {
            this.View.ShowProcessForm(formResult => { }, userTruePro, "正在执行采购件库存报表同步...");
            MainWorker.QuequeTask(this.View.Context, () =>
            {
                try
                {
                    string formId = "YCVN_PurInvReport";
                    DynamicObjectCollection schemes = KingdeeTools.GetSchemes(ctx, formId);
                    var counter = schemes.Count;
                    for (int i = 1; i < counter; i++)
                    {
                        // TODO
                        if (schemes.Count > 0)
                        {
                            string openUserName = "第三方";
                            //string kingdeeUrl = KingdeeTools.GetRequestWebUrl();
                            string kingdeeUrl = "http://10.1.16.51/K3CLOUD";
                            DynamicObject setting = KAndOSysSynTool.GetKToOSysSynSetting(ctx, "", 0);
                            string appkey = Convert.ToString(setting["FOSysURL2"]);
                            string port = "/restcloud/weaveroa/v1/rest/ofs/ReceiveRequestInfoByJson";
                            string url = KAndOSysSynTool.GetUrl(setting, port);
                            foreach (var item in schemes)
                            {
                                string workcode = Convert.ToString(item["FSCHEMENAME"]);
                                var qurey = Api.ExecuteBillQuery(ctx, "SEC_User", "FNAME", $"F_YCVN_GH='{workcode}'", "FNAME", 1);
                                if (qurey.Count > 0)
                                {
                                    openUserName = qurey.FirstOrDefault().FirstOrDefault().ToString();
                                }
                                SyncOA(ctx, workcode, url, appkey, kingdeeUrl, formId, openUserName);
                            }
                        }
                        Thread.Sleep(1000);
                        // 报告下执行进度
                        var rate = Convert.ToInt32(i * 100 / counter);
                        this.View.Session["ProcessRateValue"] = rate;
                        // 进度条界面增加文字提示信息
                        this.View.Session["ProcessTips"] = string.Format("任务{0}已处理", i);
                    }
                    this.View.ShowMessage("操作已完成。");
                }
                catch (Exception ex)
                {
                    this.View.ShowErrMessage(ex.Message);
                }
                finally
                {
                    // 此句必不可少，进度值100时进度条自动关闭
                    this.View.Session["ProcessRateValue"] = 100;
                    this.View.SendDynamicFormAction(this.View);
                }
            }, null);
        }

        private void SyncOA(Context ctx, string workcode, string url, string appkey, string kingdeeUrl, string formId, string openUserName)
        {
            DBResult result = new DBResult();
            string jsonStr = "";
            string curFlowId = Guid.NewGuid().ToString();
            string timestamp = KingdeeTools.GetTimestamp();
            string timestamp2 = KingdeeTools.GetTimestamp();
            JSONObject cJson = new JSONObject();
            JSONObject newJson = new JSONObject();
            cJson.Add("syscode", "ERPReport");
            cJson.Add("flowid", curFlowId);
            cJson.Add("requestname", $"采购件库存报表");
            cJson.Add("workflowname", $"采购件库存报表");
            cJson.Add("nodename", "采购件库存报表");
            cJson.Add("receiver", workcode);
            cJson.Add("creator", "报表");
            cJson.Add("createdatetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            cJson.Add("receivedatetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            //cJson.Add("appurl", KingdeeTools.GetMobileUrl(openUserName, "", kingdeeUrl, ctx, formId));
            cJson.Add("appurl", KingdeeTools.GetH5KindeeUrl(openUserName, "", kingdeeUrl, formId, ctx));
            cJson.Add("pcurl", KingdeeTools.GetH5KindeeUrl(openUserName, "", kingdeeUrl, formId, ctx));
            cJson.Add("receivets", timestamp);
            cJson.Add("isremark", "0");
            cJson.Add("viewtype", "0");

            newJson.Add("syscode", "ERPReport");
            newJson.Add("flowid", curFlowId);
            newJson.Add("requestname", $"采购件库存报表");
            newJson.Add("workflowname", $"采购件库存报表");
            newJson.Add("nodename", "采购件库存报表");
            newJson.Add("receiver", workcode);
            newJson.Add("creator", "报表");
            newJson.Add("createdatetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            newJson.Add("receivedatetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            //string appurl = KingdeeTools.GetMobileUrl(openUserName, "0", kingdeeUrl, ctx, formId);
            string pcurl = KingdeeTools.GetH5KindeeUrl(openUserName, "0", kingdeeUrl, formId, ctx);
            newJson.Add("appurl", pcurl);
            newJson.Add("pcurl", pcurl);
            newJson.Add("receivets", timestamp2);
            newJson.Add("isremark", "2");
            newJson.Add("viewtype", "0");

            jsonStr = cJson.ToString();
            string msg = "";
            bool isOk = false;
            try
            {
                result = InvokeHelper.Post(url, jsonStr, appkey, workcode, 0);
                msg = JsonConvert.SerializeObject(result);
                result = InvokeHelper.Post(url, newJson.ToString(), appkey, workcode, 0);
                msg = msg + JsonConvert.SerializeObject(result);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            finally
            {
                //操作日志只记录一条
                if (result.operResult == "1")
                {
                    isOk = true;
                    msg = string.Format("采购件库存报表同步OA成功！");
                }
                else
                {
                    msg = $"采购件库存报表同步OA失败！原因是：{msg}";
                }
                //记录日志
                WriteLog(ctx, msg, jsonStr, isOk, formId, "采购件库存报表", "", curFlowId);
            }
        }

        private void WriteLog(Context ctx, string msg, string jsonStr, bool isOk, string formId, string v2, string v3, string curFlowId)
        {
            SyncLog log = new SyncLog();
            log.Operation = "采购件库存报表List";
            log.FormId = formId;
            log.FbillName = "采购件库存报表";
            log.FBillNo = "";
            log.Result = msg;
            log.FOrgId = 0;
            log.Direction = curFlowId;
            log.Json = jsonStr;
            log.IsSuccess = isOk;
            KingdeeTools.SaveLog(ctx, log);
        }
    }
}
